'''
* This is the projet for Brtc LlmOps Platform
* @Author Leon-liao <liaosiliang@alltman.com>
* @Description //TODO 
* @File: 3_handle_except_for_tool.py
* @Time: 2025/10/29
* @All Rights Reserve By Brtc
'''
from typing import Any

import dotenv
from langchain_core.runnables import RunnableConfig
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI

dotenv.load_dotenv()

@tool
def complex_tool(int_arg:int, float_arg:float, dict_arg:dict)->int:
    """使用复杂工具进行计算操作"""
    return int(int_arg * float_arg)

def try_except_tool(tool_args:dict, config:RunnableConfig)->Any:
    try:
        return complex_tool.invoke(tool_args, config)
    except Exception as e:
        return f"调用工具使用以下参数:\n\n{tool_args}\n\n引发了以下错误：{e}"

#1、创建大模型并绑定工具
llm = ChatOpenAI(model = "gpt-4o-mini", temperature=0)
llm_with_tools = llm.bind_tools([complex_tool])

#2、创建链并执行工具
chain = llm_with_tools|(lambda msg:msg.tool_calls[0]["args"])|try_except_tool
#3、调用链
print(chain.invoke("使用复杂工具,对应参数为 5 和 2.1"))
